/**
 * 摄像头组件和文件上传组件
 * 版本：1.0.1
 * 日期：2018/5/8
 * 日志：
 *  1.v1.0.0 2018/5/8 创建
 *  2.v1.0.1 2018/11/20 弹窗样式修改，图标替换
 *  3.v1.0.2 2018/3/19 调整局部组件camera的位置
 */

// 为了紧急上线,暂时去除弹窗中的删除按钮，因为几个组件并没有调用删除回调函数
// 这里做提示，后期尽量加上 add by xujiaming 2019/04/12
layui.extend({
  camera: 'attach/camera'
}).define(['jquery', 'layer', 'element', 'camera', 'view', 'Http', 'helper'], function(e) {
  var $ = layui.jquery;
  var layer = layui.layer;
  var elem = layui.element;
  var view = layui.view;
  var Http = layui.Http;
  var util = layui.helper;

  var Class = function() {
    this.v = '1.0.1';
    this.config = {};
  };

  var $$path = window.$$path;

  Class.prototype.init = function(option) {
    var optUpload = option.upload || {};
    // 配置参数
    this.config.option = {
      saveType: option.saveType || 'save',
      upload  : {
        url           : $$path + '/ftpUploadController/fileUpload.json',
        maxSize       : optUpload.maxSize || '153600kb',
        multiSelection: true, // update by taogang 默认是多文件选择吧 2019年6月12日13:45:54
        params        : optUpload.params || {},
        complete      : optUpload.complete || function() {
        }
      }
    };
    // 配置样式
    setCss();
  };

  Class.prototype.render = function(option) {
    var that = this;

    that.init(option);

    view.popup({
      title  : '附件',
      area   : ['600px', '380px'],
      resize : false,
      id     : 'LAY-admin-attach',
      content: [
        '<div lay-module="attach" class="attach__container">',
        '  <div class="attach__toolbar">',
        '    <a id="attach__browse"><i class="gw-icon icon-folder-open"></i> 浏览</a>',
        '    <a id="attach__camera"><i class="layui-icon layui-icon-camera-fill"></i> 拍照</a>',
        '    <a class="layui-hide" id="attach__upload"><i class="layui-icon layui-icon-upload"></i> 上传</a>',
        '    <a id="attach__save"><i class="gw-icon icon-save"></i> 保存</a>',
        // '    <a id="attach__help"><i class="layui-icon">&#xe60b;</i> 帮助</a>',
        '  </div>',
        '  <ul class="attach__list" id="attach__files"></ul>',
        '</div>'
      ].join(''),
      success: function(_, index) {
        fileEvent(that, index);
      }
    });
  };

  Class.prototype.lookup = function(path) {
    if (!util.isString(path)) return false;

    var realPath = $$path + '/ftpUploadController/getImage?physicalPath=' + encodeURIComponent(path);
    this.check(path, function() {
      layer.open({
        type      : 1,
        title     : false,
        closeBtn  : 0,
        id        : 'layui-layer-photos',
        skin      : 'layui-layer-photos', // 没有背景色
        offset    : '30px',
        area      : '450px',
        shadeClose: true,
        success   : function(layero) {
          var $div = $('<div class="layui-layer-phimg" style="min-height: 300px"></div>');
          view.loading($div);
          layero.append($div);
          var $img = $('<img>');
          $img.attr('src', realPath).on('load', function() {
            view.removeLoad();
            $div.append($img);
          });
        }
      });
    });
  };

  Class.prototype.download = function(path) {
    if (!util.isString(path)) return false;

    var realPath = $$path + '/ftpUploadController/downLoad?physicalPath=' + encodeURIComponent(path);
    this.check(path, function() {
      top.open(realPath);
    });
  };

  Class.prototype.check = function(path, callback) {
    if (!util.isString(path)) return false;

    var realPath = $$path + '/ftpUploadController/checkExists?physicalPath=' + encodeURIComponent(path);
    var api = new Http({
      url    : realPath,
      success: function(response) {
        var data = response.data;
        if (data.isExists) {
          $.isFunction(callback) && callback();
        } else {
          api.hint('当前文件不存在');
        }
      }
    });
    api.fetch();
  };

  function indexOf(arr, val) {
    for (var i = 0; i < arr.length; i++) {
      if (arr[i].file.id === val) return i;
    }
    return -1;
  }

  function remove(arr, val) {
    var index = indexOf(arr, val);
    if (index > -1) {
      arr.splice(index, 1);
    }
  }

  function fileEvent(attach, layIndex) {
    // 运用了plupload组件
    // /////////////////////////////////////////////
    // 指定的jQuery对象
    var $scope = $('[lay-module="attach"]'); // 弹窗范围
    var $browse = $scope.find('#attach__browse'); // 触发按钮
    var $list = $scope.find('#attach__files'); // 文件队列
    var $camera = $scope.find('#attach__camera'); // 拍照
    var $save = $scope.find('#attach__save'); // 保存
    // var $upload = $scope.find('#attach__upload'); // 上传
    // 配置参数获取
    var _option = attach.config.option;
    var _upload = _option.upload; // upload参数
    var tempResult = [];// 最终结果
    var _mime_types = [ // 只允许上传图片和zip文件
      { title: 'Image files', extensions: 'jpg,gif,png,jpeg' },
      { title: 'Zip files', extensions: 'zip' },
      { title: 'Pdf files', extensions: 'pdf' },
      { title: 'Word files', extensions: 'docx,doc' },
      { title: 'Excel files', extensions: 'xlsx,xls,xlsm' }
    ];
    if (_upload.params && _upload.params.mime_types) {
      _mime_types = _upload.params.mime_types;
    }
    var _single = false;// 是否只上传一个，若为true，则每次上传覆盖掉之前的文件，且多选改为单选
    if (_upload.params && _upload.params.single) {
      _single = _upload.params.single;
      _upload.multiSelection = false;
    }
    var _deleteComplete;// 自定义删除方法
    if (_upload.params && _upload.params.deleteComplete && typeof _upload.params.deleteComplete === 'function') {
      _deleteComplete = true;
    }
    // 实例化uploader
    var uploader = new window.plupload.Uploader({
      browse_button      : $browse.get(0),
      url                : _upload.url,
      flash_swf_url      : $$path + '/plupload-v1.5.7/Moxie.swf',
      silverlight_xap_url: $$path + '/plupload-v1.5.7/Moxie.xap',
      filters            : {
        mime_types        : _mime_types,
        max_file_size     : _upload.maxSize, // 最大只能上传150mb的文件
        prevent_duplicates: true // 不允许选取重复文件
      },
      multipart_params: _upload.params,
      multi_selection : _upload.multiSelection
    });
    // 每一次的初始化页面
    var _reset = function() { // 初始化方法修改，添加传入的已存在文件存储在ftp服务器的物理地址数组，即[physicalPath1,physicalPath2,.......]
      var _files = [];
      if (_upload.params && _upload.params.files) {
        _files = _upload.params.files;
      }
      $list.attr('count', _files.length);
      if (_files.length === 0) {
        $list.html('').html('<li class="attach__center">没有上传的文件</li>');
      } else {
        $list.html('');
        var _html = '';
        var fileId = '';
        var fileName = '';
        $.each(_files, function(idx, file) { // _files不会存于uploader对象中
          fileId = '__' + idx;// 自定义fileid,用于删除，
          fileName = file.substring(file.indexOf('_') + 1, file.length);// 显示图片的名字
          _html = [
            '<li file-index="' + idx + '" file-id="' + fileId + '" file-name="' + fileName + '">',
            fileName,
            '  <div class="layui-progress" lay-filter="progress-' + fileId + '">',
            '   <div class="layui-progress-bar layui-bg-orange" lay-percent="90%"></div>',
            '  </div>',
            // '  <button id="del-' + fileId + '" file=' + file + ' type="button" class="layui-btn layui-btn-danger layui-btn-xs mydelete">删除</button>',
            '  <span class="attach__result" style="color:#28a745" id="success-' + fileId + '"><i class="gw-icon icon-correct"></i></span>',
            '</li>'
          ].join('');
          $list.append($(_html));
          elem.progress('progress-' + fileId, '100%');
        });
        $('.mydelete').click(function() {
          var $this = $(this);
          layer.alert('确认删除', function(index) {
            layer.close(index);
            new Http({
              url    : $$path + '/ftpUploadController/delete',
              data   : { physicalPath: $this.attr('file') },
              success: function(delResponse) {
                var bool = delResponse.code === 1;
                if (bool) {
                  var tempFileId = $this.attr('id').substring(4, $this.attr('id').length);
                  var $li = $list.find('li[file-id="' + tempFileId + '"]');
                  if ($li.length !== 1) {
                    layer.alert('未知错误，当前文件编号不唯一，编号为: ' + tempFileId);
                    return;
                  }
                  // 删除成功需要处理2个地方
                  // 一个是_upload.params.files
                  if (_upload.params && _upload.params.files && _upload.params.files.length > 0) {
                    var temp_files = [];
                    for (var i = 0; i < _upload.params.files.length; i++) {
                      if (_upload.params.files[i] === $this.attr('file')) {
                        continue;
                      }
                      temp_files.push(_upload.params.files[i]);
                    }
                    _upload.params.files = temp_files;
                  }
                  // 一个是页面
                  $li.slideUp(function() {
                    $li.remove();
                    var preCount = $list.attr('count'); var curCount = 0;
                    curCount = --preCount <= 0 ? 0 : preCount;
                    $list.attr('count', curCount);
                    if (preCount === 0) {
                      setTimeout(function() {
                        _reset();
                      }, 60);
                    }
                  });
                  if (_deleteComplete) {
                    _upload.params.deleteComplete($this.attr('file'));
                  }
                } else {
                  layer.msg('删除失败');
                }
              }
            }).fetch();
          });
        });
      }
    };
    // /////////////////////////////////////////////
    // 首次执行初始化
    _reset();
    // 实例对象初始化
    uploader.init();
    // 文件添加触发
    uploader.bind('FilesAdded', function(uploader, files) {
      // console.log('FilesAdded')
      var _html = '';
      if (+$list.attr('count') === 0) {
        $list.html('');
      }
      $list.attr('count', uploader.files.length);
      if (_single) {
        $list.html('');
        $list.attr('count', 1);
      }
      $.each(uploader.files, function(idx, file) {
        var fileName = file.name;
        var fileId = file.id;
        var fileSize = file.size;
        var fileStatus = file.status;
        if (fileStatus !== window.plupload.DONE) {
          _html += [
            '<li file-index="' + idx + '" file-id="' + fileId + '" file-name="' + fileName + '">',
            fileName + ' [ ' + (fileSize / 1014).toFixed(1) + 'kb ] ',
            '  <div class="layui-progress" lay-filter="progress-' + fileId + '">',
            '   <div class="layui-progress-bar layui-bg-orange" lay-percent="100%"></div>',
            '  </div>',
            '  <button id="reupload-' + fileId + '" type="button" class="layui-btn layui-btn-normal layui-btn-xs layui-hide">重命名</button>',
            // '  <button id="del-' + fileId + '" type="button" class="layui-btn layui-btn-danger layui-btn-xs layui-hide">删除</button>',
            '  <span class="attach__result layui-hide" style="color:#28a745" id="success-' + fileId + '"><i class="gw-icon icon-correct"></i></span>',
            '  <span class="attach__result layui-hide" style="color:#FF5722" id="error-' + fileId + '"><i class="layui-icon layui-icon-close-fill"></i></span>',
            '</li>'
          ].join('');
        }
      });
      var $_html = $(_html);
      $_html.find('button').off('click');
      $list.append($_html);
      uploader.disableBrowse(true);
      uploader.start();
    });
    // 进度条
    uploader.bind('UploadProgress', function(uploader, file) {
      // console.log('UploadProgress')

      file.percent = file.percent >= 90 ? 90 : file.percent;
      elem.progress('progress-' + file.id, file.percent + '%');
    });
    // 每一个文件上传结束后触发
    uploader.bind('FileUploaded', function(uploader, file, responseObject) {
      // console.log('FileUploaded')
      var fileId = file.id;
      // 进度条修改为100%
      elem.progress('progress-' + fileId, '100%');
      // 寻找相关按钮，预备使用
      var $del = $list.find('button[id="del-' + fileId + '"]');
      var $reupload = $list.find('button[id="reupload-' + fileId + '"]');
      var $success = $list.find('span[id="success-' + fileId + '"]');
      var $error = $list.find('span[id="error-' + fileId + '"]');
      // 处理返回结果, 判断上传成功与否
      if (file.status === window.plupload.DONE) {
        $success.removeClass('layui-hide');
        $error.addClass('layui-hide');
        var physicalPath = '';
        if (responseObject) {
          var type = typeof responseObject.response;
          if (type === 'string' && responseObject.response) {
            var _response = JSON.parse(responseObject.response);
            physicalPath = _response.physicalPath || '';
            if (_single) {
              tempResult = [];
            }
            tempResult.push({ file: file, result: _response });
            $del.attr('file', _response.physicalPath);// 添加标识，用于自定义删除方法
          }
        }
        // 删除按钮绑定事件
        $del.removeClass('layui-hide');

        $del.on('click', function() {
          var $this = $(this);
          layer.alert('确认删除', function(index) {
            layer.close(index);
            new Http({
              url    : $$path + '/ftpUploadController/delete',
              data   : { physicalPath: physicalPath },
              success: function(delResponse) {
                var bool = delResponse.code === 1;
                if (bool) {
                  var tempFileId = $this.attr('id').substring(4, $this.attr('id').length);
                  var $li = $list.find('li[file-id="' + tempFileId + '"]');
                  if ($li.length !== 1) {
                    layer.alert('未知错误，当前文件编号不唯一，编号为: ' + tempFileId);
                    return;
                  }
                  // 删除的文件按钮移除
                  $this.off('click');
                  $this.addClass('layui-hide');
                  // 删除成功需要处理2个地方
                  // 一个是uploader实例
                  uploader.removeFile(uploader.getFile(fileId));
                  // 删除tempResult
                  remove(tempResult, fileId);
                  // console.log(tempResult)
                  // 一个是页面
                  $li.slideUp(function() {
                    $li.remove();
                    var preCount = $list.attr('count'); var curCount = 0;
                    curCount = --preCount <= 0 ? 0 : preCount;
                    $list.attr('count', curCount);
                    if (preCount === 0) {
                      setTimeout(function() {
                        _reset();
                      }, 60);
                    }
                  });
                  if (_deleteComplete) { // 自定义删除
                    _upload.params.deleteComplete($this.attr('file'));
                  }
                } else {
                  layer.msg('删除失败');
                }
              }
            }).fetch();
          });
        });
      } else {
        $error.removeClass('layui-hide');
        $success.addClass('layui-hide');
        $reupload.removeClass('layui-hide');
        $reupload.on('click', function() {
          // 单独上传
        });
      }
    });
    // 所有文件上传后触发
    uploader.bind('UploadComplete', function(uploader, files) {
      // console.log('UploadComplete')
      uploader.disableBrowse(false);
    });
    // 调用摄像头
    $camera.on('click', function() {
      layui.camera.render(function(file, name, layIndex) {
        if (typeof file.isCanvas === 'undefined') {
          // 这里由开始处理file => blob，处理blob需要自己携带文件名
          // uploader.addFile(file)
          uploader.addFile(file, name);
        } else {
          layer.msg('摄像头获取照片失败');
        }
        layer.close(layIndex);
      });
    });
    // 保存
    $save.on('click', function() {
      _upload.complete(tempResult, layIndex);
      layer.close(layIndex);
    });
  }

  function setCss() {
    if (document.querySelector('#attach__style')) return;
    // 组装样式
    var styleNode = document.createElement('style');
    var cssString = '' +
            '.attach__center{text-align:center}' +
            // '.attach__container{padding:12px 15px;}' +
            '.attach__toolbar{margin:0 0 7px;padding:8px 10px;border:solid 1px #a8c7ce;border-radius:2px;background-color:#dae8f1;}' +
            '.attach__toolbar>a{margin-right:10px;user-select: none;cursor: pointer;}' +
            '.attach__toolbar:after{content:" ";dispaly:table;clear:both;}' +
            '.attach__list{max-height:260px;overflow-y:auto;padding:0 6px;border:1px solid #ddd;border-radius:2px;}' +
            '.attach__list>li{position:relative;padding:5px 10px;line-height:1.42857143;border-bottom:1px solid #ddd;}' +
            '.attach__list>li:last-child{border-bottom:none;}' +
            '.attach__list>li>.layui-progress{display:inline-block;width:50px;}' +
            '.attach__list>li>.layui-btn + .layui-btn {margin-left:0;}' +
            '.attach__list>li>.attach__result{position:absolute;right:6px;z-index:1;}' +
            '.attach__list>li>.attach__result>i{font-size:18px;}';
    styleNode.id = 'attach__style';
    styleNode.type = 'text/css';
    if (styleNode.styleSheet) {
      styleNode.styleSheet.cssText = cssString;
    } else {
      styleNode.innerHTML = cssString; // styleNode.appendChild(document.createTextNode(cssString))
    }
    document.getElementsByTagName('head')[0].appendChild(styleNode);
  }

  e('attach', new Class());
})
;
